<template>
  <div class="container">
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input v-model="formInline.keyword" placeholder="根据文章标题搜索" type="text" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formInline.state" placeholder="请选择">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleClear">清除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button type="success" @click="handleAdd"><i class="el-icon-edit" />新增技巧</el-button>
        </el-form-item>
      </el-form>
      <template>
        <div class="tips">
          <i class="el-icon-info" />
          <span>数据一共{{ total }}条</span>
        </div>
      </template>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe>
        <el-table-column type="index" :index="handleIndex" label="序号" width="150" />
        <el-table-column prop="title" label="文章标题" width="300" />
        <el-table-column prop="visits" label="阅读数" width="100" />
        <el-table-column prop="username" label="录入人" width="120" />
        <el-table-column prop="createTime" label="录入时间" width="250">
          <template #default="{row}">
            {{ formatTimeData(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="120">
          <template #default="{row}">
            已{{ formatHireType(row.state) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" prop="state" fixed="right">
          <template #default="{row}">
            <!-- handlePreview(row.id) -->
            <el-button type="text" size="medium" @click="handlePreview(row)">预览</el-button>
            <el-button type="text" size="medium" @click="handleStatus(row)">{{ row.state ? "禁用" : "启用" }}</el-button>
            <el-button type="text" size="medium" :disabled="row.state ? true : false" @click="handleEdit(row)">修改</el-button>
            <el-button type="text" size="medium" :disabled="row.state ? true : false" @click="handleDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template>
        <!-- 分页 -->
        <el-pagination background layout="->, prev, pager,next,sizes,jumper" :page-size="queryData.pagesize" :current-page.sync="queryData.page" :page-sizes="[10, 20, 30, 40]" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </template>
    </el-card>
    <!-- 新增文章对话框组件 -->
    <ArticlesAdd :show-dialog.sync="showDialog" :edit-item="editItem" :flag="flag" />
    <!-- 预览文章对话框 -->
    <!-- <ArticlesPreview :show-dialog.sync="showPreviewDialog" /> -->

    <articles-preview :pre-data="preData" :show-preview-dialog.sync="showPreviewDialog" />

  </div>
</template>

<script>
import moment from "moment";
import { status } from "@/api/hmmm/constants.js"
import { list, changeState, remove } from "@/api/hmmm/articles.js"
import ArticlesAdd from '@/module-hmmm/components/articles-add.vue'
import ArticlesPreview from '@/module-hmmm/components/articles-preview.vue'
export default {
  name: 'Articles',
  components: { ArticlesAdd, ArticlesPreview },
  // components: { pageTool },
  data () {
    return {
      flag: false,
      // 预览的当前数据
      preData: {},
      // 点击当前修改的id
      editItem: {},

      // 预览文章对话框状态
      showPreviewDialog: false,
      // changeStatus: false,
      // 新增对话框状态
      showDialog: false,
      // 编辑状态
      // flag: false,
      // 加载状态
      loading: false,
      // 表单数据
      formInline: {
        keyword: '',
        state: null,
      },
      // 列表总数
      total: 0,
      // 分页参数
      queryData: {
        page: 1,
        pagesize: 10,

      },
      // 表格数据
      tableData: [],

    }
  },
  created () {
    this.GetArticlesList()
  },
  methods: {
    // =====================================清空关键字输入框
    handleClear () {
      this.formInline.keyword = ""
    },

    // ==================================== 搜索
    async handleSearch () {
      if (this.formInline.keyword.trim === "") {
        this.GetArticlesList()
      } else {
        const res = await list({
          ...this.queryData,
          ...this.formInline
        })
        if (res.status === 200) {
          this.tableData = res.data.items
        }
      }
    },

    // =========================================== 点击删除
    handleDel (row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await remove(row)
        if (res.status === 200) {
          this.$message.success('删除成功')
          this.GetArticlesList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // ===========================================点击新增
    handleAdd () {
      this.showDialog = true
      this.flag = false
    },
    // ========================================== 点击修改文章信息
    async handleEdit (row) {
      this.showDialog = true
      this.editItem = row
      this.flag = true
    },

    // ========================================================控制操作状态
    async handleStatus (row) {
      // 将state值反转(如果state为1时取0,反之取1)
      row.state = row.state === 0 ? 1 : 0
      const res = await changeState(row)
      if (res.status === 200) {
        // 如果调用成功,刷新列表
        this.GetArticlesList()
        this.$message.success("操作成功")
      }
    },

    // ============================================================ 格式化状态文本
    formatHireType (type) {
      const obj = status.find(item => parseInt(item.value) === parseInt(type))
      if (obj) {
        return obj.label
      } else {
        this.status = "其他"
      }
    },
    // ================================================================= 预览文章
    handlePreview (row) {
      // 预览弹窗打开
      this.showPreviewDialog = true
      this.preData = row
      // console.log(this.preData);
    },
    // 分页: 每页多少条数据
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    // 实现分页
    handleCurrentChange (index) {
      // 当前点击哪页把哪页的页数传过来
      this.queryData.page = index
      // 加载当前点击的哪页数据列表
      this.GetArticlesList()
    },
    // 计算动态索引
    handleIndex (index) {
      // 形参index表示列表数据的索引,从0开始
      // 动态计算累加索引
      // (当前页码-1)*每页的条数
      const { page, pagesize } = this.queryData
      return (page - 1) * pagesize + 1 + index
    },
    // 时间格式化
    formatTimeData (val) {
      return moment(val).format("yyyy-MM-DD hh:mm:ss");
    },
    // 获取文章列表
    async GetArticlesList () {
      this.loading = true
      try {
        const res = await list(this.queryData)
        // console.log(res);
        if (res.status === 200) {
          this.tableData = res.data.items
          this.total = res.data.counts
          // this.$options(this.tableData)
        }
      } catch {
        this.$message('获取文章列表失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 10px 8px;
  .tips {
    padding: 10px 16px;
    border-radius: 3px;
    color: #909399;
    font-size: 13px;
    background-color: #f4f4f5;
    margin-bottom: 15px;
    // height: 20px !important;
    .el-icon-info {
      margin-right: 5px;
    }
  }
}
</style>
